package com.user.notiy.pool;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.user.notiy.dao.TNoticeMapper;


@Component("BeanDefineConfigue")
public class NoticeThreadPool implements ApplicationListener<ContextRefreshedEvent> {
	private static Logger log = LoggerFactory.getLogger(NoticeThreadPool.class);

	@Autowired
	private TNoticeMapper tNoticeDAO;
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent arg0) {
		List<Map<String, Object>> noticeInfos= tNoticeDAO.getNoticeInfo();
		
		log.info("创建线程池...共需创建[" + noticeInfos.size() + "]个");
		ExecutorService noticeThreadPool = Executors.newFixedThreadPool(noticeInfos.size());

		/* 设置入惨 */
		Class[] paramTypes = {String.class, String.class, String.class, TNoticeMapper.class};
		
		for(final Map<String, Object> noticeInfo : noticeInfos) {
			log.info("线程池增加[" + noticeInfo.get("NOTICE_POOL_NAME") + "]号线程，线程处理方法为[" + noticeInfo.get("NOTICE_CLASS") + "]...");

			try {
				/* 获取Class对象 */
				Class obj = Class.forName(noticeInfo.get("NOTICE_CLASS").toString());
				/* 获取构造 */
				Constructor<NoticeThread> con = obj.getConstructor(paramTypes);
				/* 设置入惨 */
				Object[] params = {noticeInfo.get("NOTICE_POOL_NAME"), noticeInfo.get("NOTICE_TYPE"), noticeInfo.get("NOTICE_GROUP"), tNoticeDAO};
				/* 创建实例 */
				NoticeThread thread = con.newInstance(params);
				/* 加入线程池 */
				noticeThreadPool.execute(thread);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				log.error("创建[" + noticeInfo.get("NOTICE_CLASS") + "]失败！");
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			}
		}
	}
}
